package PrjHttpUtils

import "net/http"

var (
	basic_user string
	basic_pass string
)

func ConfigHttpAuthBasic(user, pass string) {
	basic_user, basic_pass = user, pass
}

func DoHttpAuthBasic(w http.ResponseWriter, r *http.Request) bool {
	usr, pass, hasAuth := r.BasicAuth()

	if (basic_user == "" && basic_pass == "") ||
		(hasAuth && usr == basic_user && pass == basic_pass) {
		return true
	} else {
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
	}
	return false

}

func HttpBasicAuth(h http.HandlerFunc, user, passwd string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		reqUser, reqPasswd, hasAuth := r.BasicAuth()
		if (user == "" && passwd == "") ||
			(hasAuth && reqUser == user && reqPasswd == passwd) {
			h.ServeHTTP(w, r)
		} else {
			w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		}
	}
}
